/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RecipeEditorIngredients.java
 *
 * Created on 2011-04-20, 15:28:00
 */
package other;

import java.awt.Color;
import java.util.Vector;
import javax.swing.Action;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import model.Ingredient;
import model.Measure;
import model.Product;
import model.Recipe;
import sun.misc.Cleaner;

/**
 *
 * @author krzysztof
 */
public class RecipeEditorIngredients extends javax.swing.JFrame {

    Recipe actualRecipe;
    private RecipeEditor recipeEditor;
    private boolean deleteFlag = false;

    /** Creates new form RecipeEditorIngredients */
    public RecipeEditorIngredients() {
        initComponents();
    }

    RecipeEditorIngredients(Recipe recipe, RecipeEditor rEditor) {
        this();
        actualRecipe = recipe;
        recipeEditor = rEditor;
        refreshTable();
    }

    private void refreshTable() {
        Vector listIngredients = actualRecipe.listIngredients();
        int sizeI = listIngredients.size();
        String ingredient[] = new String[sizeI];
        String measure[] = new String[sizeI];
        String amount[] = new String[sizeI];
        for (int i = 0; i < sizeI; i++) {
            Ingredient first = (Ingredient) listIngredients.elementAt(i);
            try {
                ingredient[i] = first.getProduct().getName().toString();
            } catch (NullPointerException e) {
                ingredient[i] = "";
            }
            Measure miara = first.getMeasure();
            measure[i] = miara.getName();
            amount[i] = miara.getAmount();
        }
        String[] names = {"nazwa", "ilość", "miara"};
        DefaultTableModel defaultTableModel = new DefaultTableModel(names, sizeI);
        for (int i = 0; i < sizeI; i++) {
            defaultTableModel.setValueAt(ingredient[i], i, 0);
            defaultTableModel.setValueAt(amount[i], i, 1);
            defaultTableModel.setValueAt(measure[i], i, 2);

        }

        jTable1.setModel(defaultTableModel);

        for (int i = 0; i < sizeI; i++)
            jTextPane1.setText(jTextPane1.getText() + ingredient[i] + " " + amount[i] + " " + measure[i] + "\n");

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabelSkladniki = new javax.swing.JLabel();
        jButtonDodajSkladnik = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jLabel1 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cookbookdesktop.CookbookDesktopApp.class).getContext().getResourceMap(RecipeEditorIngredients.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel1.setBackground(resourceMap.getColor("jPanel1.background")); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setBackground(resourceMap.getColor("jTable1.background")); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, "", null}
            },
            new String [] {
                "Skladnik", "Ilosc", "Miara"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                rowClickListener(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabelSkladniki.setText(resourceMap.getString("jLabelSkladniki.text")); // NOI18N
        jLabelSkladniki.setName("jLabelSkladniki"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(cookbookdesktop.CookbookDesktopApp.class).getContext().getActionMap(RecipeEditorIngredients.class, this);
        jButtonDodajSkladnik.setAction(actionMap.get("addIngridient")); // NOI18N
        jButtonDodajSkladnik.setBackground(resourceMap.getColor("jButtonDodajSkladnik.background")); // NOI18N
        jButtonDodajSkladnik.setText(resourceMap.getString("jButtonDodajSkladnik.text")); // NOI18N
        jButtonDodajSkladnik.setName("jButtonDodajSkladnik"); // NOI18N

        jButton1.setAction(actionMap.get("saveChangesAndClose")); // NOI18N
        jButton1.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTextPane1.setName("jTextPane1"); // NOI18N
        jScrollPane2.setViewportView(jTextPane1);

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jCheckBox1.setAction(actionMap.get("deleteIngredient")); // NOI18N
        jCheckBox1.setBackground(resourceMap.getColor("jCheckBox1.background")); // NOI18N
        jCheckBox1.setText(resourceMap.getString("jCheckBox1.text")); // NOI18N
        jCheckBox1.setName("jCheckBox1"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                    .addComponent(jLabelSkladniki, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jButtonDodajSkladnik)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 105, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(39, 39, 39)
                        .addComponent(jCheckBox1)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelSkladniki)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jCheckBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonDodajSkladnik)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void rowClickListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_rowClickListener
        // TODO add your handling code here:
        if (deleteFlag) {
            JTable aTable = (JTable) evt.getSource();
            int itsRow = aTable.rowAtPoint(evt.getPoint());


            int sizeI = jTable1.getModel().getRowCount();
            String P[] = new String[sizeI];
            Product products[] = new Product[sizeI];
            Measure measures[] = new Measure[sizeI];

            DefaultTableModel defaultTableModel = (DefaultTableModel) jTable1.getModel();


            for (int i = 0; i < sizeI; i++) {
                measures[i] = new Measure((String) defaultTableModel.getValueAt(i, 2), (String) defaultTableModel.getValueAt(i, 1));
                products[i] = new Product((String) defaultTableModel.getValueAt(i, 0), measures[i], 0);
            }

            actualRecipe.listIngredients().clear();


            for (int i = 0; i < sizeI; i++) {
                if (i != itsRow) {
                    Ingredient ingredient = new Ingredient(products[i], measures[i]);
                    actualRecipe.addIngredient(ingredient);
                }
            }

            jTable1.setModel(defaultTableModel);
//            actualRecipe.getActivities().remove(itsRow);

            recipeEditor.savetRecipe();
            jTextPane1.setText(null);
            refreshTable();
        }
    }//GEN-LAST:event_rowClickListener

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new RecipeEditorIngredients().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonDodajSkladnik;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabelSkladniki;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables

    public Recipe getActualRecipe() {
        return actualRecipe;
    }

    public void setActualRecipe(Recipe actualRecipe) {
        this.actualRecipe = actualRecipe;
    }

    void setActualRecipe(Vector listIngredients) {
    }

    @org.jdesktop.application.Action
    public void addIngridient() {
        saveChanges();
        jTextPane1.setText(null);   // zerowanie pola, bo kolejna metoda je uzupełni
        refreshTable();
    }

    @org.jdesktop.application.Action
    public void saveChangesAndClose() {
        this.setVisible(false);
        //saveChanges();
    }

    @org.jdesktop.application.Action
    public void saveChanges() {

        Vector listIngredients = new Vector();
        int sizeI = jTable1.getModel().getRowCount();
        String ingredient[] = new String[sizeI+1024];
        String measure[] = new String[sizeI+1024];
        String amount[] = new String[sizeI+1024];

        String[] oneLine;
        String allIngridientString = "";
        String[] linesOfAllText = jTextPane1.getText().split("\\\n");
        sizeI = linesOfAllText.length;

        for (int i = 0; i < sizeI; i++) {
            oneLine = linesOfAllText[i].split(" ");
            if (oneLine.length > 2) {
                allIngridientString=oneLine[0];
                for (int j = 1; j <= oneLine.length - 3; j++) {
                    allIngridientString = allIngridientString + " " +oneLine[j];
                }
                ingredient[i] = allIngridientString;
                amount[i] = oneLine[oneLine.length - 2];
                measure[i] = oneLine[oneLine.length - 1];
            }
            else if(oneLine.length == 2){
                ingredient[i] = oneLine[0];
                measure[i] = oneLine[1];
                amount[i] = "";
            }
            else if(oneLine.length == 1){
                ingredient[i] = oneLine[0];
                measure[i]="";
                amount[i] = "";
            }
            else {
                ingredient[i] = "";
                measure[i]="";
                amount[i] = "";
            }
        }

        actualRecipe.listIngredients().clear();

        for (int i = 0; i < sizeI; i++) {

            Ingredient ing = new Ingredient(new Product(ingredient[i], new Measure(measure[i], amount[i]), 0), new Measure(measure[i], amount[i]));
            actualRecipe.addIngredient(ing);

        }

    }

                @org.jdesktop.application.Action
    public void deleteIngredient() {
        if (deleteFlag) {
            deleteFlag = false;
        } else {
            deleteFlag = true;
        }
    }
}
